#include "app_mqtt.h"
#include "log/log.h"
#include "MQTTClient.h"
#include <string.h>

static MQTTClient client;
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
static MQTTClient_message pubmsg = MQTTClient_message_initializer;
static int (*recv_callback)(char *json) = NULL;

 //消息确认处理函数处理 参数： 上下文  确认标记
void delivered(void *context, MQTTClient_deliveryToken dt)
{
    log_debug("发送消息成功");
}
 
//接收消息的回调函数处理 参数： 上下文  主题名  主题长度  消息
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    int result = 0; //0:成功  1:失败 默认0
    if (recv_callback)
    {
        result = recv_callback((char *)message->payload) == 0 ? 1 : 0;
    }
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return result;
}
//断线回调函数处理
void connlost(void *context, char *cause)
{
    log_debug(" 连接断开 cause: %s\n", cause);
}
int app_mqtt_init(void)
{
    //初始化客户端
    if(MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL)!= MQTTCLIENT_SUCCESS)
    {
        log_error("创建客户端失败");
        return -1;
    }
    //设置回调函数
    if(MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered)!= MQTTCLIENT_SUCCESS)
    {
        log_error("设置回调函数失败");
        MQTTClient_destroy(&client);
        return -1;
    }

    //连接服务器
    if(MQTTClient_connect(client, &conn_opts)!= MQTTCLIENT_SUCCESS)
    {
        log_error("连接服务器失败");
        MQTTClient_destroy(&client);
        return -1;
    }
    //订阅主题
    if(MQTTClient_subscribe(client, TOPIC_RTG, QOS)!= MQTTCLIENT_SUCCESS)
    {
        log_error("订阅主题失败");
        MQTTClient_disconnect(client, TIMEOUT);
        MQTTClient_destroy(&client);
        return -1;
    }
    log_debug("客户端初始化成功");
    return 0;
}

void app_mqtt_close(void)
{
    MQTTClient_unsubscribe(client, TOPIC_RTG);
    MQTTClient_disconnect(client, TIMEOUT);
    MQTTClient_destroy(&client);
}

int app_mqtt_send(char *json)
{
    pubmsg.payload = json;
    pubmsg.payloadlen = strlen(json);
    pubmsg.qos = QOS;
    if(MQTTClient_publishMessage(client, TOPIC_GTR, &pubmsg, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_error("发布消息失败");
        return -1;
    }
    log_debug("向远程发送消息：%s", json);
    return 0;
}

void app_mqtt_registerRecvCallback(int (*callback)(char *json))
{
    recv_callback = callback;
}
